package com.fjnu.exception;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 全局异常处理切面，处理标记@ExceptionGlobalCatch的Service类
 */
@Aspect
@Component
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Around("@within(com.fjnu.annotation.ExceptionGlobalCatch)")
    public Object handleServiceException(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            return joinPoint.proceed(); // 执行原方法
        } catch (Exception e) {
            logger.error("Service方法异常: {}，方法名: {}",
                    e.getMessage(), joinPoint.getSignature().getName(), e);
            // 根据返回值类型返回默认失败结果
            org.aspectj.lang.reflect.MethodSignature methodSignature = (org.aspectj.lang.reflect.MethodSignature) joinPoint.getSignature();
            Class<?> returnType = methodSignature.getReturnType();
            if (returnType == int.class) {
                return 0; // 整数返回0表示失败
            } else if (returnType == void.class) {
                return null; // 无返回值
            } else {
                return null; // 对象类型返回null
            }
        }
    }
}